package com.frxuexi.mymvi

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class MessViewModel @Inject constructor(private val messRepository: MessRepository):ViewModel() {

    //获取一个存放意图的管道
    val channel= Channel<MessIntent>(Channel.UNLIMITED)

    //获取一个可变状态，用于更新UI
    private val _state= MutableStateFlow<MessState>(MessState.onLoading)
    val state:StateFlow<MessState>
        get() = _state


    init {
        viewModelScope. launch {
            channel.receiveAsFlow().collect{
                when(it){
                    is MessIntent.getMess->{
                        getMess(it.page)
                    }
                }
            }
        }
    }

    fun getMess(page:Int){
        viewModelScope.launch {
            messRepository.getMess(page)
                .flowOn(Dispatchers.IO)
                .catch {
                    Log.i("===",it.message.toString())
                }
                .collect{
                    if(it.code==0){
                        _state.value=MessState.onSuccess(it.data.records)
                    }else{
                        _state.value=MessState.onError(it.msg)
                    }
                }
        }
    }
}